<template>
	<view>
    <!-- 商品列表 -->
		<view class="goods-list">
		  <view v-for="(goods, i) in goodsList" :key="i" @click="gotoDetail(goods)">
        <my-goods :goods="goods"></my-goods>
      </view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
        // 请求参数对象
				queryObj: {
          // 搜索关键字
          query: '',
          // 商品分类id
          cid: '',
          // 页码值
          pageNum: 1,
          // 每页显示的条数
          pageSize: 10
        },
        // 商品列表
        goodsList: [],
        total: 0,
        // 节流阀
        isloading: false
			};
		},
    onLoad(options) {
      this.queryObj.query = options.query || '',
      this.queryObj.cid = options.cid || ''
      this.getGoodsList()
    },
    methods: {
      // 获取商品列表数据
      async getGoodsList (cb) {
        // 打开节流阀
        const {data: res} = await uni.$http.get('/api/public/v1/goods/search', this.queryObj)
        // 关闭节流阀
        if (res.meta.status !== 200) return uni.$showMsg()
        cb && cb()
        this.goodsList = [...this.goodsList, ...res.message.goods]
        this.total = res.message.total
      },
      // 点击商品跳转到商品详情页
      gotoDetail (goods) {
        uni.navigateTo({
          url: '../goods_detail/goods_detail?goods_id=' + goods.goods_id
        })
      }
    },
    // 上拉加载数据
    onReachBottom () {
      if (this.queryObj.pageNum * this.queryObj.pageSize >= this.total) return uni.$showMsg('数据加载完毕')
      // 判断节流阀有没有打开,打开说明在加载数据，就不需要再发起请求
      if (this.isloading) return
      this.queryObj.pageNum ++,
      this.getGoodsList()
    },
    // 下拉刷新
    onPullDownRefresh() {
      // 重置数据
      this.queryObj.pageNum = 1
      this.isloading = false
      this.total = 0
      this.goodsList = []
      // 重新发起数据请求
      this.getGoodsList(() => {
        // 请求结束关闭下拉刷新
        uni.stopPullDownRefresh()
      })
    }
	}
</script>

<style lang="scss">

</style>
